﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Drawing;
using System.IO;
using System.Windows.Forms;
using System.Xml;
using Assist;
using Autodesk.Revit.DB;
using Autodesk.Revit.UI;
using FlexCell;
using YArchitech.Controls;
using YArchitech.LIB;
using YArchitech.LIB.YJKControls;
using HyCommonTableTool;
using HyDrawSelectArea;
using HyMaterialStatistic;
using HYView;
using Transfer.Utils;

namespace YJKArch.StatisticTable
{
	public partial class DlgFastMaterialStatistic : System.Windows.Forms.Form
	{
		public DlgFastMaterialStatistic(ExternalCommandData commandData, WindowHandle _hWndRevit, FastMaterialRequestHandler handler, ExternalEvent exEvent, bool bDoorWnd = false)
		{
			this.InitializeComponent();
			this.m_cmmdData = commandData;
			this.m_doc = commandData.Application.ActiveUIDocument.Document;
			this.m_hWndRevit = _hWndRevit;
			this.m_Handler = handler;
			this.m_ExEvent = exEvent;
			this.m_bDoorWnd = bDoorWnd;
			if (!Directory.Exists(this.m_strPreviewPath))
			{
				YJKMessageBox.Show("找不到模板文件");
				return;
			}
			string[] array;
			if (this.m_bDoorWnd)
			{
				array = new string[]
				{
					"门窗表1",
					"门窗表2",
					"门窗表3"
				};
			}
			else
			{
				array = Directory.GetFiles(this.m_strPreviewPath, "*.hymb");
			}
			foreach (string path in array)
			{
				this.cmbGrid.Items.Add(Path.GetFileNameWithoutExtension(path));
			}
			if (this.cmbGrid.Items.Count > 0)
			{
				this.cmbGrid.SelectedIndex = 0;
			}
			this.rdoProject.Checked = true;
			this.m_lstViewPlan = FloorSelectManager.GetAllFloorViewPlan(this.m_doc);
		}

		private void GetGridSetInfo(string strFilePath)
		{
			XmlDocument xmlDocument = new XmlDocument();
			xmlDocument.Load(strFilePath);
			XmlElement xmlElement = xmlDocument.DocumentElement.SelectSingleNode("GridInfo") as XmlElement;
			if (xmlElement == null)
			{
				return;
			}
			this.m_gridSet.FontSize = Convert.ToSingle(xmlElement.GetAttribute("FontSize"));
			this.m_gridSet.TitleFontSize = Convert.ToSingle(xmlElement.GetAttribute("TitleFontSize"));
			this.m_gridSet.FontName = xmlElement.GetAttribute("FontName");
			this.m_gridSet.LineWidthOut = Convert.ToInt32(xmlElement.GetAttribute("LineWidthOut"));
			this.m_gridSet.LineWidthInner = Convert.ToInt32(xmlElement.GetAttribute("LineWidthInner"));
		}

		private void btnCreate_Click(object sender, EventArgs e)
		{
			this.m_gridSet.GridName = this.txtGridName.Text;
			this.m_gridSet.LinkFile = this.chkLink.Checked;
			this.m_gridSet.NewView = this.chkNewView.Checked;
			if (this.rdoLevel.Checked && (this.cmbGrid.Text == "门窗表2" || this.cmbGrid.Text == "门窗表3") && this.m_standardLevel.Count < 1)
			{
				MessageBox.Show("没有选择楼层标高");
				return;
			}
			this.MakeRequest(RequestId.DrawGrid);
		}

		public void DrawGrid()
		{
			base.Hide();
			FlexCell.Grid grid =  new FlexCell.Grid();
			if (!this.InitialGridData(ref grid))
			{
				return;
			}
			CREATENEWVIEW newView;
			if (this.chkNewView.Checked)
			{
				newView = CREATENEWVIEW.NEWVIEW;
			}
			else
			{
				newView = CREATENEWVIEW.EXIST;
			}
			GridToolExportImportRevit gridToolExportImportRevit = new GridToolExportImportRevit(this.m_cmmdData, grid, this.txtGridName.Text, this.m_gridSet.LineWidthOut, this.m_gridSet.LineWidthInner, newView);
			int nStaticType;
			if (this.rdoArea.Checked)
			{
				nStaticType = 2;
			}
			else if (this.rdoLevel.Checked)
			{
				nStaticType = 1;
			}
			else
			{
				nStaticType = 0;
			}
			gridToolExportImportRevit.SetRefreshData(this.m_doc.ActiveView, nStaticType, this.m_lstViewPlan, this.m_standardLevel, this.m_lstSelAreaCurve, this.m_gridSet);
			gridToolExportImportRevit.DrawInRevitView();
			base.Close();
		}

		private bool InitialGridData(ref FlexCell.Grid grid)
		{
			string fileName = this.m_strFolderPath + "\\" + this.cmbGrid.Text + ".hymb";
			if (!grid.LoadFromXML(fileName))
			{
				return false;
			}
			this.m_gridSet.TemplateName = this.cmbGrid.Text;
			if (this.cmbGrid.Text == "门窗表1")
			{
				DoorWindowGrid1 doorWindowGrid = new DoorWindowGrid1(this.m_doc, this.m_gridSet, ref grid);
				if (this.rdoArea.Checked)
				{
					return doorWindowGrid.GetStatisticGrid(this.m_lstSelElems);
				}
				return doorWindowGrid.GetStatisticGrid(this.m_lstViewPlan);
			}
			else if (this.cmbGrid.Text == "门窗表2")
			{
				DoorWindowGrid2 doorWindowGrid2 = new DoorWindowGrid2(this.m_doc, this.m_gridSet, ref grid);
				if (this.rdoArea.Checked)
				{
					return doorWindowGrid2.GetStatisticGrid(this.m_lstSelElems);
				}
				if (this.rdoLevel.Checked)
				{
					return doorWindowGrid2.GetStatisticGrid(this.m_lstViewPlan, this.m_standardLevel);
				}
				return doorWindowGrid2.GetStatisticGrid(this.m_lstViewPlan);
			}
			else if (this.cmbGrid.Text == "门窗表3")
			{
				DoorWindowGrid3 doorWindowGrid3 = new DoorWindowGrid3(this.m_doc, this.m_gridSet, ref grid);
				if (this.rdoArea.Checked)
				{
					return doorWindowGrid3.GetStatisticGrid(this.m_lstSelElems);
				}
				if (this.rdoLevel.Checked)
				{
					return doorWindowGrid3.GetStatisticGrid(this.m_lstViewPlan, this.m_standardLevel);
				}
				return doorWindowGrid3.GetStatisticGrid(this.m_lstViewPlan);
			}
			else if (this.cmbGrid.Text == "外墙做法")
			{
				OutsideWallGrid outsideWallGrid = new OutsideWallGrid(this.m_doc, this.m_gridSet, ref grid);
				if (this.rdoArea.Checked)
				{
					return outsideWallGrid.GetStatisticGrid(this.m_lstSelElems, this.m_doc.ActiveView.GenLevel);
				}
				return outsideWallGrid.GetStatisticGrid(this.m_lstViewPlan);
			}
			else if (this.cmbGrid.Text == "屋面做法表")
			{
				RoofsGrid roofsGrid = new RoofsGrid(this.m_doc, this.m_gridSet, ref grid);
				if (this.rdoArea.Checked)
				{
					return roofsGrid.GetStatisticGrid(this.m_lstSelElems);
				}
				return roofsGrid.GetStatisticGrid(this.m_lstViewPlan);
			}
			else if (this.cmbGrid.Text == "自动扶梯选型表")
			{
				EscalatorGrid escalatorGrid = new EscalatorGrid(this.m_doc, this.m_gridSet, ref grid);
				if (this.rdoArea.Checked)
				{
					return escalatorGrid.GetStatisticGrid(this.m_lstSelElems);
				}
				return escalatorGrid.GetStatisticGrid(this.m_lstViewPlan);
			}
			else if (this.cmbGrid.Text == "电梯选型表")
			{
				ElevatorGrid elevatorGrid = new ElevatorGrid(this.m_doc, this.m_gridSet, ref grid);
				if (this.rdoArea.Checked)
				{
					return elevatorGrid.GetStatisticGrid(this.m_lstSelElems);
				}
				return elevatorGrid.GetStatisticGrid(this.m_lstViewPlan);
			}
			else
			{
				if (this.cmbGrid.Text == "图纸目录")
				{
					return new SheetScheduleGrid(this.m_doc, this.m_gridSet, ref grid).GetStatisticGrid();
				}
				return this.cmbGrid.Text == "图纸总目录" && new GeneralSheetScheduleGrid(this.m_doc, this.m_gridSet, ref grid).GetStatisticGrid();
			}
		}

		private void btnExcel_Click(object sender, EventArgs e)
		{
			this.m_gridSet.GridName = this.txtGridName.Text;
			this.m_gridSet.LinkFile = this.chkLink.Checked;
			this.m_gridSet.NewView = this.chkNewView.Checked;
			this.MakeRequest(RequestId.ExportExl);
		}

		public void ExportExcel()
		{
			base.Hide();
			SaveFileDialog saveFileDialog = new SaveFileDialog();
			saveFileDialog.FileName = this.txtGridName.Text;
			saveFileDialog.Filter = "Excel文件|*.xls|Excel文件|*.xlsx|盈建科表格文件|*.hybg";
			if (saveFileDialog.ShowDialog() == DialogResult.OK)
			{
				FlexCell.Grid grid =  new FlexCell.Grid();
				if (!this.InitialGridData(ref grid))
				{
					return;
				}
				int filterIndex = saveFileDialog.FilterIndex;
				if (filterIndex != 1)
				{
					if (filterIndex == 2)
					{
						new GridToolExportImportExcel(true).ExportExcel(grid, saveFileDialog.FileName);
					}
				}
				else
				{
					new GridToolExportImportExcel(false).ExportExcel(grid, saveFileDialog.FileName);
				}
				base.Close();
			}
		}

		private void cmbGrid_SelectedIndexChanged(object sender, EventArgs e)
		{
			this.txtGridName.Text = this.cmbGrid.Text;
			this.m_gridSet.GridName = this.txtGridName.Text;
			string strFilePath = this.m_strFolderPath + "\\" + this.cmbGrid.Text + ".hymb";
			this.GetGridSetInfo(strFilePath);
			if (this.cmbGrid.Text == "图纸目录")
			{
				this.rdoProject.Enabled = false;
				this.rdoLevel.Enabled = false;
				this.rdoArea.Enabled = false;
				return;
			}
			this.rdoProject.Enabled = true;
			this.rdoLevel.Enabled = true;
			this.rdoArea.Enabled = true;
		}

		private void btnSet_Click(object sender, EventArgs e)
		{
			base.Hide();
			List<string> columnListInfo = this.GetColumnListInfo();
			new DlgColumnSetCommon(this.cmbGrid.Text, this.m_strPreviewPath, columnListInfo, ref this.m_gridSet).ShowDialog();
			base.Show();
		}

		private List<string> GetColumnListInfo()
		{
			List<string> list = new List<string>();
			if (this.cmbGrid.Text == "门窗表1")
			{
				list.Add("类别");
				list.Add("设计编号");
				list.Add("宽");
				list.Add("高");
				list.Add("樘数");
				list.Add("图集代号");
				list.Add("编号");
				list.Add("备注");
			}
			else if (this.cmbGrid.Text == "门窗表2")
			{
				list.Add("类别");
				list.Add("设计编号");
				list.Add("洞口尺寸");
				list.Add("楼层名称");
				list.Add("楼层名称");
				list.Add("总计");
				list.Add("图集名称");
				list.Add("页次");
				list.Add("选用型号");
				list.Add("备注");
			}
			else if (this.cmbGrid.Text == "门窗表3")
			{
				list.Add("类别");
				list.Add("设计编号");
				list.Add("宽度");
				list.Add("高度");
				list.Add("楼层名称");
				list.Add("楼层名称");
				list.Add("总樘数");
				list.Add("图集号");
				list.Add("页次编号");
				list.Add("备注");
			}
			else if (this.cmbGrid.Text == "外墙做法")
			{
				list.Add("编号");
				list.Add("名称");
				list.Add("标准图索引");
				list.Add("备注");
			}
			else if (this.cmbGrid.Text == "屋面做法表")
			{
				list.Add("编号");
				list.Add("名称");
				list.Add("标准图索引");
				list.Add("备注");
			}
			else if (this.cmbGrid.Text == "自动扶梯选型表")
			{
				list.Add("名称");
				list.Add("扶梯编号");
				list.Add("倾斜角度");
				list.Add("梯级宽度");
				list.Add("额定速度(m/s)");
				list.Add("输送能力(人/h)");
				list.Add("护臂板特征");
				list.Add("备注");
			}
			else if (this.cmbGrid.Text == "电梯选型表")
			{
				list.Add("名称");
				list.Add("电梯编号");
				list.Add("额定载重量(kg)");
				list.Add("额定速度(m/s)");
				list.Add("层数");
				list.Add("站数");
				list.Add("提升高度(m)");
				list.Add("台数");
				list.Add("备注");
			}
			else if (this.cmbGrid.Text == "图纸目录")
			{
				list.Add("序号");
				list.Add("图号");
				list.Add("图纸名称");
				list.Add("图幅");
				list.Add("备注");
			}
			else if (!(this.cmbGrid.Text == "室内装修做法表1") && !(this.cmbGrid.Text == "室内装修做法表2") && !(this.cmbGrid.Text == "室内装修做法表3") && this.cmbGrid.Text == "图纸总目录")
			{
				list.Add("序号");
				list.Add("图号");
				list.Add("图纸名称");
				list.Add("序号");
				list.Add("图号");
				list.Add("图纸名称");
				list.Add("序号");
				list.Add("图号");
				list.Add("图纸名称");
				list.Add("序号");
				list.Add("图号");
				list.Add("图纸名称");
				list.Add("序号");
				list.Add("图号");
				list.Add("图纸名称");
				list.Add("序号");
				list.Add("图号");
				list.Add("图纸名称");
			}
			return list;
		}

		private void btnCancel_Click(object sender, EventArgs e)
		{
			base.Close();
		}

		private void DlgMaterialStatistic_Load(object sender, EventArgs e)
		{
			base.Icon = Resource.YArchitechIcon;
		}

		private void rdoProject_Click(object sender, EventArgs e)
		{
			this.m_lstViewPlan = FloorSelectManager.GetAllFloorViewPlan(this.m_doc);
		}

		private void rdoLevel_Click(object sender, EventArgs e)
		{
			if (this.cmbGrid.Text == "门窗表2" || this.cmbGrid.Text == "门窗表3")
			{
				SelectFloorForm selectFloorForm = new SelectFloorForm(DlgFastMaterialStatistic.GetSortLevels(this.m_doc, double.MinValue, double.MaxValue));
				if (selectFloorForm.ShowDialog() == DialogResult.OK)
				{
					this.m_standardLevel = selectFloorForm.getStandardLevels();
					return;
				}
			}
			else
			{
				List<Level> levels = new List<Level>();
				if (FloorSelectManager.SelectLevel(this.m_doc, ref levels, null))
				{
					this.UpdateViewPlan(levels);
				}
			}
		}

		public static List<Level> GetSortLevels(Autodesk.Revit.DB.Document doc, double bottom, double top)
		{
			List<Level> list = new List<Level>();
			foreach (Element element in new FilteredElementCollector(doc).OfClass(typeof(Level)).ToElements())
			{
				Level level = element as Level;
				double elevation = level.Elevation;
				if (elevation >= bottom && elevation <= top)
				{
					list.Add(level);
				}
			}
			list.Sort(new DlgFastMaterialStatistic.LevelComparer());
			return list;
		}

		private void UpdateViewPlan(List<Level> levels)
		{
			this.m_lstViewPlan.Clear();
			if (levels.Count <= 0)
			{
				return;
			}
			List<ViewPlan> list = new List<ViewPlan>();
			List<double> list2 = new List<double>();
			foreach (Element element in new FilteredElementCollector(this.m_doc).OfClass(typeof(ViewPlan)))
			{
				ViewPlan viewPlan = element as Autodesk.Revit.DB.ViewPlan;
				if (viewPlan != null && (int)viewPlan.ViewType == 1 && viewPlan.GenLevel != null)
				{
					list2.Add(viewPlan.GenLevel.Elevation);
					list.Add(viewPlan);
				}
			}
			for (int i = 0; i < levels.Count; i++)
			{
				for (int j = 0; j < list2.Count; j++)
				{
					if (Geometry.IsEqual(levels[i].Elevation, list2[j]))
					{
						this.m_lstViewPlan.Add(list[j]);
					}
				}
			}
		}

		private void rdoArea_Click(object sender, EventArgs e)
		{
			this.MakeRequest(RequestId.SelectArea);
		}

		public void SelectStatisticArea()
		{
			if (this.m_lstSelElems != null)
			{
				this.m_lstSelElems.Clear();
			}
			base.Hide();
			CmdViewType types = CmdViewType.FloorPlan;
			if (SwitchView.SetUsableView(types, this.m_cmmdData) != Autodesk.Revit.UI.Result.Succeeded)
			{
				YJKMessageBox.Show("请在平面视图中框选区域");
				return;
			}
			if (SelectAreaManager._hWndRevit == null)
			{
				SelectAreaManager._hWndRevit = this.m_hWndRevit;
			}
			SelectAreaManager selectAreaManager = new SelectAreaManager(this.m_cmmdData);
			try
			{
				if (selectAreaManager.EditOutLine() != null)
				{
					YJKMessageBox.Show("选择区域失败");
				}
				if (selectAreaManager.m_lstDetailCurveId.Count <= 0)
				{
					base.Show(this.m_hWndRevit);
					return;
				}
				this.RecordSelAreaCurve(selectAreaManager.m_lstDetailCurveId);
				CollectSelAreaElement collectSelAreaElement = new CollectSelAreaElement(this.m_cmmdData.Application);
				this.m_lstSelElems = collectSelAreaElement.CollectAllElementInArea(this.chkLink.Checked, this.m_doc.ActiveView, selectAreaManager.m_lstDetailCurveId);
				this.DeleteSelectLine(selectAreaManager.m_lstDetailCurveId);
			}
			catch
			{
				YJKMessageBox.Show("选择区域失败");
				this.DeleteSelectLine(selectAreaManager.m_lstDetailCurveId);
			}
			base.Show(this.m_hWndRevit);
		}

		private void RecordSelAreaCurve(List<ElementId> lstCurveId)
		{
			int num = 0;
			int num2 = 0;
			foreach (ElementId elementId in lstCurveId)
			{
				Element element = this.m_doc.GetElement(elementId);
				if (element != null)
				{
					SelectAreaCurve selectAreaCurve = new SelectAreaCurve();
					Curve curve = (element.Location as LocationCurve).Curve;
					if (curve is Line)
					{
						selectAreaCurve.CurveName = "Line" + num.ToString();
						XYZ endPoint = curve.GetEndPoint(0);
						XYZ endPoint2 = curve.GetEndPoint(1);
						selectAreaCurve.Points.Add(endPoint);
						selectAreaCurve.Points.Add(endPoint2);
						num++;
					}
					else
					{
						selectAreaCurve.CurveName = "Arc" + num2.ToString();
						XYZ endPoint3 = curve.GetEndPoint(0);
						XYZ endPoint4 = curve.GetEndPoint(1);
						double endParameter = curve.GetEndParameter(0);
						double endParameter2 = curve.GetEndParameter(1);
						double num3 = (endParameter + endParameter2) * 0.5;
						XYZ item = curve.Evaluate(num3, true);
						selectAreaCurve.Points.Add(endPoint3);
						selectAreaCurve.Points.Add(endPoint4);
						selectAreaCurve.Points.Add(item);
						num2++;
					}
					this.m_lstSelAreaCurve.Add(selectAreaCurve);
				}
			}
		}

		public void DeleteSelectLine(List<ElementId> lstSelLineId)
		{
			Transaction transaction = new Transaction(this.m_doc, "Delete SelArea Line");
			transaction.Start();
			try
			{
				this.m_doc.Delete(lstSelLineId);
				transaction.Commit();
			}
			catch
			{
				transaction.RollBack();
			}
		}

		private void DlgFastMaterialStatistic_FormClosed(object sender, FormClosedEventArgs e)
		{
			if (this.m_ExEvent != null)
			{
				this.m_ExEvent.Dispose();
				this.m_ExEvent = null;
				this.m_Handler = null;
				base.OnFormClosed(e);
			}
		}

		private void MakeRequest(RequestId request)
		{
			this.m_Handler.Request.Make(request);
			this.m_ExEvent.Raise();
		}

		private void DlgFastMaterialStatistic_KeyDown(object sender, KeyEventArgs e)
		{
			if (e.KeyCode == Keys.Escape)
			{
				base.Close();
			}
		}

		private string m_strPreviewPath = Path.Combine(Product.InstallLocation, "Templates", "StatisticTempletlFile");

		private ExternalCommandData m_cmmdData;

		private Autodesk.Revit.DB.Document m_doc;

		private WindowHandle m_hWndRevit;

		private List<Element> m_lstSelElems;

		private List<ViewPlan> m_lstViewPlan = new List<ViewPlan>();

		private GridSetCommonInfo m_gridSet = new GridSetCommonInfo();

		private FastMaterialRequestHandler m_Handler;

		private ExternalEvent m_ExEvent;

		private bool m_bDoorWnd;

		private string m_strFolderPath = Path.Combine(Product.InstallLocation, "Templates", "StatisticTempletlFile");

		private List<SelectAreaCurve> m_lstSelAreaCurve = new List<SelectAreaCurve>();

		private List<StandardLevel> m_standardLevel = new List<StandardLevel>();

		private class LevelComparer : IComparer<Level>
		{
			public int Compare(Level x, Level y)
			{
				return x.Elevation.CompareTo(y.Elevation);
			}
		}
	}
}
